#!/bin/sh

ip=`/sbin/ifconfig -a eth0|grep inet|awk '{print $2}'|tr -d "addr:"|sed -n '1p'`
hostname=`hostname`
groupName="els" #组名
elPort="9200"
watchPath="/xsyx/server/logs/*.log" #组名


#gen logstash config
sudo mkdir -p /usr/logstash/config
sudo chmod 777 /usr/logstash/config
sudo rm -rf /usr/logstash/config/logstash.conf
sudo rm -rf /usr/logstash/config/logstash.yml


#logstash 创建配置
if [ ! -f "/usr/logstash/config/logstash.conf" ];then
writeLogstashStr='
input {
  file {
    path => "'${watchPath}'"
    type => "'${hostname}'-logs"
    start_position => "beginning"
  }
}

filter {
    multiline {
      pattern => "%{DATESTAMP}"
      negate => true
      what => "previous"
    }

   grok {
      match => {"message" => "\[%{DATA:time_local}\] \[%{LOGLEVEL:log_level}\]  %{GREEDYDATA:pomele_message}"}
      remove_field=>"message"
   }

    date {
      match => ["time_local", "yy/MM/dd-HH:mm:ss.SSS"]
    }
}

output {
  stdout{codec=>"rubydebug"}
  elasticsearch {
     hosts => ["'${ip}':'${elPort}'"]
     index => "'${hostname}'--%{+YYYY.MM.dd}"
     document_type   => ${hostname}
  }
}'

echo "${writeLogstashStr}">> /usr/logstash/config/logstash.conf
fi


# logstash.yml
#生成配置表 kibana
if [ ! -f "/usr/logstash/config/logstash.yml" ];then
    echo 'http.host: "0.0.0.0"'>> /usr/logstash/config/logstash.yml
    echo 'xpack.monitoring.elasticsearch.hosts: [ "http://'${ip}':9200" ]'>> /usr/logstash/config/logstash.yml
    echo '#xpack.monitoring.elasticsearch.username: elastic'>> /usr/logstash/config/logstash.yml
    echo '#xpack.monitoring.elasticsearch.password: changeme'>> /usr/logstash/config/logstash.yml
fi
